﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.SqlServer.Query.ExpressionTranslators.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using MQTTnet.AspNetCore;
using MQTTnet.Protocol;
using MQTTnet.Server;

namespace AspNetCoreMqtt
{
    public class Startup
    {
        private ILogger<Startup> _logger;

        public Startup(IConfiguration configuration,ILogger<Startup> logger)
        {
            Configuration = configuration;
            _logger = logger;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddHostedMqttServer(option =>
            {
                //option.WithDefaultEndpoint();
                option.WithDefaultEndpointPort(1883);
                option.WithApplicationMessageInterceptor((context) =>
                {
                    _logger.Log(LogLevel.Information, $"clientId:{context.ClientId}, topic:{context.ApplicationMessage.Topic}");
                    _logger.Log(LogLevel.Information,$"Payload:{Encoding.Default.GetString(context.ApplicationMessage.Payload)}");
                });
                option.WithSubscriptionInterceptor((context) =>
                {
                    //context.TopicFilter.Topic.start
                });
                option.WithConnectionValidator(c =>
                {
                    if (c.Username != "admin" || c.Password != "admin")
                    {
                        c.ReturnCode = MqttConnectReturnCode.ConnectionRefusedBadUsernameOrPassword;
                        return;
                    }

                    c.ReturnCode = MqttConnectReturnCode.ConnectionAccepted;

                });
            });
            services.AddMqttTcpServerAdapter();
            services.AddMqttWebSocketServerAdapter();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseMqttServer(server =>
            {
                //开始
                server.StartedHandler = new MqttServerStartedHandlerDelegate(
                    (args) =>
                    {
                        return Task.Run(() =>
                        {

                        });
                    }
                );

                //停止
                server.StoppedHandler = new MqttServerStoppedHandlerDelegate((args) =>
                {
                    return Task.Run(() =>
                    {

                    });
                });

                server.UseClientConnectedHandler(
                    (args) =>
                    {
                        return Task.Run(() =>
                        {

                        });
                    });
                server.UseClientDisconnectedHandler(
                    (args) =>
                    {
                        return Task.Run(() =>
                        {

                        });
                    });
            });

            app.UseMqttEndpoint();

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
